import sys
import os
import subprocess
import logging
import toml
import datetime
import html
import re
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from config_manager import Config
import psutil

# 读取版本配置
def load_version_config():
    """从config.toml读取版本号"""
    try:
        config_path = os.path.join(os.path.dirname(__file__), "config.toml")
        if os.path.exists(config_path):
            with open(config_path, 'r', encoding='utf-8') as f:
                config = toml.load(f)
                return config.get('version', {}).get('number', "UNKNOWN")
        else:
            logging.warning("config.toml文件不存在，使用默认版本号")
            return '20250725a2'
    except Exception as e:
        logging.error(f"读取版本配置失败: {e}")
        return '20250725a2'

# 设置日志文件
def setup_logging():
    """设置日志系统，同时输出到文件和控制台"""
    # 生成带时间戳的日志文件名
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    log_filename = f"{timestamp}_hae.log"
    log_path = os.path.join(os.path.dirname(__file__), log_filename)
    
    # 创建根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    
    # 清除现有的处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 创建格式化器
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    
    # 文件处理器
    file_handler = logging.FileHandler(log_path, encoding='utf-8')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    root_logger.addHandler(file_handler)
    
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    
    logging.info(f"日志系统初始化完成，日志文件: {log_filename}")
    return log_path

# 初始化日志系统
LOG_FILE_PATH = setup_logging()
VERSION = load_version_config()

# 加载自定义字体
def load_custom_font():
    """加载自定义字体"""
    try:
        # 加载思源宋体
        font_path = os.path.join(os.path.dirname(__file__), "assets", "fonts", "SourceHanSerifSC-Medium.otf")
        if os.path.exists(font_path):
            font_id = QFontDatabase.addApplicationFont(font_path)
            if font_id != -1:
                font_families = QFontDatabase.applicationFontFamilies(font_id)
                if font_families:
                    logging.info(f"成功加载思源宋体: {font_families[0]}")
                    return font_families[0]
        
        logging.warning("未找到SourceHanSerifSC-Medium字体文件，使用默认字体")
        return "Microsoft YaHei"
    except Exception as e:
        logging.error(f"加载字体失败: {e}")
        return "Microsoft YaHei"  # 备用字体

class ConsoleHandler(logging.Handler):
    """自定义日志处理器，将日志输出到控制台文本框，支持多彩输出"""
    def __init__(self, text_widget):
        super().__init__()
        self.text_widget = text_widget
        
        # 定义不同日志级别的颜色
        self.level_colors = {
            'DEBUG': '#95A5A6',      # 灰色
            'INFO': '#2ECC71',       # 绿色
            'WARNING': '#F39C12',    # 橙色
            'ERROR': '#E74C3C',      # 红色
            'CRITICAL': '#8E44AD'    # 紫色
        }
        
        # 定义关键词颜色
        self.keyword_colors = {
            '成功': '#2ECC71',
            '失败': '#E74C3C',
            '错误': '#E74C3C',
            '警告': '#F39C12',
            '完成': '#2ECC71',
            '初始化': '#3498DB',
            '连接': '#3498DB',
            '找到': '#2ECC71',
            '未找到': '#E74C3C',
            '搜索': '#F39C12',
            '配置': '#9B59B6',
            '更新': '#3498DB'
        }
        
    def emit(self, record):
        try:
            # 格式化原始消息
            msg = self.format(record)
            
            # 提取时间戳和消息内容
            parts = msg.split(' - ', 2)
            if len(parts) >= 3:
                timestamp = parts[0]
                level = parts[1]
                message = parts[2]
                
                # 构建HTML格式的消息
                html_msg = self.format_html_message(timestamp, level, message)
            else:
                # 如果格式不符合预期，使用默认颜色
                html_msg = f'<span style="color: #ECF0F1;">{html.escape(msg)}</span>'
            
            # 在主线程中更新UI
            QMetaObject.invokeMethod(
                self.text_widget, 
                "append", 
                Qt.QueuedConnection, 
                Q_ARG(str, html_msg)
            )
        except Exception as e:
            # 如果出错，使用原始消息
            QMetaObject.invokeMethod(
                self.text_widget, 
                "append", 
                Qt.QueuedConnection, 
                Q_ARG(str, msg)
            )
    
    def format_html_message(self, timestamp, level, message):
        """格式化HTML消息"""
        # 时间戳样式（灰色，小字体）
        timestamp_html = f'<span style="color: #95A5A6; font-size: 11px;">{html.escape(timestamp)}</span>'
        
        # 日志级别样式
        level_color = self.level_colors.get(level, '#ECF0F1')
        level_html = f'<span style="color: {level_color}; font-weight: bold;">[{html.escape(level)}]</span>'
        
        # 消息内容样式（应用关键词高亮）
        message_html = self.highlight_keywords(html.escape(message))
        
        return f'{timestamp_html} {level_html} {message_html}'
    
    def highlight_keywords(self, message):
        """高亮关键词"""
        for keyword, color in self.keyword_colors.items():
            pattern = re.escape(keyword)
            replacement = f'<span style="color: {color}; font-weight: bold;">{keyword}</span>'
            message = re.sub(pattern, replacement, message, flags=re.IGNORECASE)
        
        # 如果没有关键词匹配，使用默认颜色
        if not any(keyword in message for keyword in self.keyword_colors.keys()):
            message = f'<span style="color: #ECF0F1;">{message}</span>'
        
        return message

class SteamFinder(QThread):
    """Steam路径查找线程"""
    found_signal = pyqtSignal(str)
    progress_signal = pyqtSignal(str)
    
    def run(self):
        self.progress_signal.emit("🔍 正在搜索Steam路径...")
        
        # 常见Steam路径
        common_paths = [
            "C:/Program Files (x86)/Steam/steamapps/common/Counter-Strike Global Offensive/game",
            "C:/Program Files/Steam/steamapps/common/Counter-Strike Global Offensive/game",
            "D:/Steam/steamapps/common/Counter-Strike Global Offensive/game",
            "E:/Steam/steamapps/common/Counter-Strike Global Offensive/game",
            "F:/Steam/steamapps/common/Counter-Strike Global Offensive/game",
            "G:/Steam/steamapps/common/Counter-Strike Global Offensive/game"
        ]
        
        # 首先检查常见路径
        for path in common_paths:
            if os.path.exists(path):
                self.found_signal.emit(path.replace("\\", "/"))
                return
                
        # 如果常见路径都没找到，搜索所有驱动器
        self.progress_signal.emit("🔍 在所有驱动器中搜索...")
        for drive in ['C:', 'D:', 'E:', 'F:', 'G:', 'H:']:
            if os.path.exists(drive):
                self.search_in_drive(drive)
                
        self.progress_signal.emit("❌ 未找到CS2安装路径")
        
    def search_in_drive(self, drive):
        """在指定驱动器中搜索"""
        try:
            for root, dirs, files in os.walk(drive):
                if "Counter-Strike Global Offensive" in root and "game" in root:
                    if os.path.exists(os.path.join(root, "csgo")):
                        self.found_signal.emit(root.replace("\\", "/"))
                        return
        except:
            pass

class AnimatedButton(QPushButton):
    """带动画效果的按钮"""
    def __init__(self, text, font_family="Microsoft YaHei"):
        super().__init__(text)
        self.font_family = font_family
        self.setStyleSheet(f"""
            QPushButton {{
                background: rgba(52, 152, 219, 0.9);
                color: white;
                border: 2px solid rgba(52, 152, 219, 0.8);
                border-radius: 8px;
                font-size: 14px;
                font-weight: 600;
                padding: 12px 18px;
                font-family: '{font_family}';
                text-align: center;
                min-height: 18px;
                line-height: 1.3;
            }}
            QPushButton:hover {{
                background: rgba(52, 152, 219, 1.0);
                border: 2px solid rgba(52, 152, 219, 1.0);
            }}
            QPushButton:pressed {{
                background: rgba(41, 128, 185, 1.0);
                border: 2px solid rgba(41, 128, 185, 1.0);
                padding: 13px 17px 11px 19px;
            }}
            QPushButton:disabled {{
                background: rgba(127, 140, 141, 0.5);
                color: rgba(255, 255, 255, 0.5);
                border: 2px solid rgba(127, 140, 141, 0.3);
            }}
        """)
    
    def animate_scale(self):
        """保留方法以兼容现有代码"""
        pass

class CS2Launcher(QMainWindow):
    def __init__(self):
        super().__init__()
        self.config = Config()
        self.cs2_path = ""
        self.finder_thread = None
        
        # 加载并设置自定义字体
        self.font_family = load_custom_font()
        self.setup_global_font()
        
        self.init_ui()
        self.load_settings()
        
    def setup_global_font(self):
        """设置全局字体"""
        font = QFont(self.font_family, 12)  # 增大基础字体大小
        QApplication.instance().setFont(font)
        
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口标题和图标
        self.setWindowTitle("哈e CS2启动器")
        self.setMinimumSize(1100, 750)  # 增加最小尺寸，防止界面挤压
        self.resize(1150, 700)  # 设置初始尺寸
        self.setWindowIcon(QIcon("logo.png"))
        
        # 设置窗口样式
        self.setStyleSheet(f"""
            QMainWindow {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(44, 62, 80, 1.0), 
                    stop:0.3 rgba(52, 73, 94, 1.0),
                    stop:0.7 rgba(44, 62, 80, 1.0),
                    stop:1 rgba(52, 73, 94, 1.0));
                border-radius: 15px;
            }}
            QGroupBox {{
                font-size: 20px;
                font-weight: bold;
                color: #ECF0F1;
                border: 2px solid rgba(52, 152, 219, 0.6);
                border-radius: 12px;
                margin-top: 15px;
                padding-top: 10px;
                background: rgba(52, 73, 94, 0.3);
                font-family: '{self.font_family}';
            }}
            QGroupBox::title {{
                subcontrol-origin: margin;
                left: 15px;
                padding: 5px 15px;
                background: rgba(52, 152, 219, 0.8);
                border-radius: 8px;
                color: white;
            }}
        """)
        
        # 主容器
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QHBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 左侧主要内容区域
        left_widget = QWidget()
        left_widget.setStyleSheet("""
            QWidget {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(15, 20, 25, 0.95), stop:1 rgba(25, 35, 45, 0.95));
            }
        """)
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(30, 30, 30, 30)
        left_layout.setSpacing(25)
        
        # 标题
        title = QLabel("🎮 哈e CS2启动器")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet(f"""
            QLabel {{
                font-size: 36px;
                font-weight: bold;
                color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(52, 152, 219, 1.0), stop:1 rgba(155, 89, 182, 1.0));
                margin-bottom: 20px;
                padding: 15px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1, 
                    stop:0 rgba(52, 152, 219, 0.1), stop:1 rgba(155, 89, 182, 0.1));
                border-radius: 15px;
                border: 2px solid rgba(52, 152, 219, 0.3);
                font-family: '{self.font_family}';
            }}
        """)
        left_layout.addWidget(title)
        
        # Steam路径设置组
        path_group = QGroupBox("Steam路径设置")
        path_group.setStyleSheet(f"""
            QGroupBox {{
                font-size: 18px;
                font-weight: bold;
                color: #ECF0F1;
                border: none;
                margin-top: 10px;
                padding-top: 10px;
                background: transparent;
                font-family: '{self.font_family}';
            }}
            QGroupBox::title {{
                subcontrol-origin: margin;
                left: 0px;
                padding: 0px;
                background: transparent;
                border: none;
                color: #ECF0F1;
            }}
        """)
        path_layout = QVBoxLayout(path_group)
        path_layout.setSpacing(15)
        
        # 路径显示标签
        self.path_label = QLabel("Steam路径: 未设置")
        self.path_label.setStyleSheet(f"""
            QLabel {{
                color: #BDC3C7;
                font-size: 14px;
                padding: 8px 12px;
                background: rgba(52, 73, 94, 0.2);
                border-radius: 8px;
                border: 1px solid rgba(52, 73, 94, 0.4);
                min-height: 16px;
                line-height: 1.2;
                font-family: '{self.font_family}';
            }}
        """)
        path_layout.addWidget(self.path_label)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 2px solid rgba(52, 73, 94, 0.5);
                border-radius: 8px;
                background: rgba(52, 73, 94, 0.2);
                text-align: center;
                color: #ECF0F1;
                font-weight: 600;
                height: 20px;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(52, 152, 219, 0.8), stop:1 rgba(41, 128, 185, 0.8));
                border-radius: 6px;
            }
        """)
        path_layout.addWidget(self.progress_bar)
        
        # Steam路径设置区域的按钮容器
        steam_buttons_container = QWidget()
        steam_buttons_layout = QHBoxLayout(steam_buttons_container)
        steam_buttons_layout.setContentsMargins(0, 0, 0, 0)
        steam_buttons_layout.setSpacing(10)
        
        # 自动搜索按钮
        self.search_btn = AnimatedButton("🔍 自动搜索", self.font_family)
        self.search_btn.clicked.connect(self.search_steam_path)
        steam_buttons_layout.addWidget(self.search_btn)
        
        # 手动选择按钮
        self.browse_btn = AnimatedButton("📁 手动选择", self.font_family)
        self.browse_btn.clicked.connect(self.browse_steam_path)
        steam_buttons_layout.addWidget(self.browse_btn)
        
        path_layout.addWidget(steam_buttons_container)
        left_layout.addWidget(path_group)
        
        # 服务器配置组
        server_group = QGroupBox("服务器配置")
        server_group.setStyleSheet(path_group.styleSheet())
        server_layout = QVBoxLayout(server_group)
        server_layout.setSpacing(15)
        
        # 输入框样式
        input_style = f"""
            QLineEdit {{
                background: rgba(44, 62, 80, 0.9);
                color: #ECF0F1;
                border: 2px solid rgba(52, 152, 219, 0.6);
                border-radius: 8px;
                padding: 10px 12px;
                font-size: 14px;
                font-family: '{self.font_family}';
                selection-background-color: rgba(52, 152, 219, 0.6);
                min-height: 20px;
                line-height: 1.3;
            }}
            QLineEdit:focus {{
                border: 2px solid rgba(52, 152, 219, 1.0);
                background: rgba(44, 62, 80, 1.0);
            }}
            QLineEdit:hover {{
                border: 2px solid rgba(52, 152, 219, 0.8);
                background: rgba(44, 62, 80, 0.95);
            }}
        """
        
        # 服务器地址
        addr_layout = QHBoxLayout()
        addr_label = QLabel("服务器地址:")
        addr_label.setStyleSheet(f"color: #ECF0F1; font-size: 14px; font-weight: 600; min-width: 90px; font-family: '{self.font_family}'; line-height: 1.4; min-height: 18px;")
        self.server_input = QLineEdit()
        self.server_input.setPlaceholderText("例如: sh_aliyun2.vincentzyu233.cn:20723")
        self.server_input.setText(self.config.get("server_address", "sh_aliyun2.vincentzyu233.cn:20723"))
        self.server_input.setStyleSheet(input_style)
        addr_layout.addWidget(addr_label)
        addr_layout.addWidget(self.server_input)
        server_layout.addLayout(addr_layout)
        
        # 服务器密码
        pass_layout = QHBoxLayout()
        pass_label = QLabel("服务器密码:")
        pass_label.setStyleSheet(f"color: #ECF0F1; font-size: 14px; font-weight: 600; min-width: 90px; font-family: '{self.font_family}'; line-height: 1.4; min-height: 18px;")
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("输入服务器密码")
        self.password_input.setText(self.config.get("server_password", "VincentZyu"))
        # self.password_input.setEchoMode(QLineEdit.Password)  # 移除密码模式
        self.password_input.setStyleSheet(input_style)
        pass_layout.addWidget(pass_label)
        pass_layout.addWidget(self.password_input)
        server_layout.addLayout(pass_layout)
        
        # 服务器配置区域的按钮容器
        server_buttons_container = QWidget()
        server_buttons_layout = QHBoxLayout(server_buttons_container)
        server_buttons_layout.setContentsMargins(0, 0, 0, 0)
        server_buttons_layout.setSpacing(10)
        
        # 更新配置按钮
        self.update_btn = AnimatedButton("⚙️ 更新配置", self.font_family)
        self.update_btn.clicked.connect(self.update_autoexec)
        server_buttons_layout.addWidget(self.update_btn)
        
        # 启动游戏按钮
        self.launch_btn = AnimatedButton("🚀 启动CS2", self.font_family)
        self.launch_btn.clicked.connect(self.launch_cs2)
        server_buttons_layout.addWidget(self.launch_btn)
        
        server_layout.addWidget(server_buttons_container)
        left_layout.addWidget(server_group)
        
        # 状态标签
        self.status_label = QLabel("✅ 准备就绪")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet(f"""
            QLabel {{
                color: #2ECC71;
                font-size: 20px;
                font-weight: 700;
                padding: 15px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(46, 204, 113, 0.1), stop:1 rgba(39, 174, 96, 0.1));
                border-radius: 10px;
                border: 2px solid rgba(46, 204, 113, 0.4);
                font-family: '{self.font_family}';
                min-height: 22px;
                line-height: 1.3;
            }}
        """)
        left_layout.addWidget(self.status_label)
        
        # 添加左侧内容到主布局
        main_layout.addWidget(left_widget, 2)
        
        # 右侧控制台区域
        right_widget = QWidget()
        right_widget.setFixedWidth(350)
        right_widget.setStyleSheet("""
            QWidget {
                background: rgba(25, 35, 45, 0.95);
                border-left: 2px solid rgba(52, 152, 219, 0.3);
            }
        """)
        right_layout = QVBoxLayout(right_widget)
        right_layout.setContentsMargins(15, 30, 30, 30)
        right_layout.setSpacing(15)
        
        # 控制台标题和按钮
        console_header = QHBoxLayout()
        console_title = QLabel("🖥️ 调试控制台")
        console_title.setStyleSheet(f"""
            QLabel {{
                font-size: 18px;
                font-weight: bold;
                color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(236, 240, 241, 1.0), stop:1 rgba(189, 195, 199, 1.0));
                font-family: '{self.font_family}';
                padding: 8px;
                min-height: 20px;
                line-height: 1.3;
            }}
        """)
        
        # 清空日志按钮
        self.console_btn = AnimatedButton("🗑️ 清空", self.font_family)
        self.console_btn.setFixedSize(100, 40)
        self.console_btn.clicked.connect(self.clear_console)
        
        console_header.addWidget(console_title)
        console_header.addStretch()
        console_header.addWidget(self.console_btn)
        right_layout.addLayout(console_header)
        
        # 控制台文本框
        self.console_text = QTextEdit()
        self.console_text.setReadOnly(True)
        self.console_text.setStyleSheet(f"""
            QTextEdit {{
                background: rgba(44, 62, 80, 0.9);
                color: #ECF0F1;
                border: 2px solid rgba(52, 152, 219, 0.4);
                border-radius: 8px;
                padding: 12px;
                font-size: 13px;
                font-family: '{self.font_family}';
                selection-background-color: rgba(52, 152, 219, 0.6);
                line-height: 1.4;
            }}
            QScrollBar:vertical {{
                background: rgba(52, 73, 94, 0.5);
                width: 12px;
                border-radius: 6px;
            }}
            QScrollBar::handle:vertical {{
                background: rgba(52, 152, 219, 0.7);
                border-radius: 6px;
                min-height: 20px;
            }}
            QScrollBar::handle:vertical:hover {{
                background: rgba(52, 152, 219, 0.9);
            }}
        """)
        right_layout.addWidget(self.console_text)
        
        # 版本号标签 - 位于控制台下方
        self.version_label = QLabel(f"版本号：{VERSION}")
        self.version_label.setAlignment(Qt.AlignCenter)
        self.version_label.setStyleSheet(f"""
            QLabel {{
                color: white;
                font-size: 16px;
                font-weight: 700;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(52, 152, 219, 0.9), stop:1 rgba(155, 89, 182, 0.9));
                border: 2px solid rgba(52, 152, 219, 0.6);
                border-radius: 12px;
                padding: 12px 20px;
                margin: 8px;
                font-family: '{self.font_family}';
                text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
                transition: all 0.3s ease;
            }}
            QLabel:hover {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(52, 152, 219, 1.0), stop:1 rgba(155, 89, 182, 1.0));
                border: 2px solid rgba(52, 152, 219, 0.8);
                transform: scale(1.05);
            }}
        """)
        right_layout.addWidget(self.version_label)
        
        # 添加右侧控制台到主布局
        main_layout.addWidget(right_widget, 1)
        
        # 设置控制台日志处理器
        console_handler = ConsoleHandler(self.console_text)
        console_handler.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        console_handler.setFormatter(formatter)
        logging.getLogger().addHandler(console_handler)
        
        logging.info(f"CS2启动器初始化完成 - 版本: {VERSION}")
        logging.info(f"日志文件路径: {LOG_FILE_PATH}")
        
    def search_steam_path(self):
        """搜索Steam路径"""
        self.search_btn.setEnabled(False)
        self.progress_bar.setVisible(True)
        self.progress_bar.setRange(0, 0)
        
        logging.info("开始搜索Steam路径...")
        
        self.finder_thread = SteamFinder()
        self.finder_thread.found_signal.connect(self.on_steam_found)
        self.finder_thread.progress_signal.connect(self.update_status)
        self.finder_thread.finished.connect(self.on_search_finished)
        self.finder_thread.start()
        
    def on_steam_found(self, path):
        """找到Steam路径时的回调"""
        self.cs2_path = path
        self.path_label.setText(f"Steam路径: {path}")
        self.path_label.setStyleSheet(f"""
            QLabel {{
                color: #2ECC71;
                font-size: 14px;
                padding: 12px;
                background: rgba(46, 204, 113, 0.1);
                border-radius: 8px;
                border: 1px solid rgba(46, 204, 113, 0.3);
                font-family: '{self.font_family}';
            }}
        """)
        self.update_status("✅ 找到CS2安装路径")
        logging.info(f"找到CS2路径: {path}")
        
    def on_search_finished(self):
        """搜索完成时的回调"""
        self.search_btn.setEnabled(True)
        self.progress_bar.setVisible(False)
        
    def browse_steam_path(self):
        """手动选择Steam路径"""
        path = QFileDialog.getExistingDirectory(
            self, 
            "选择CS2游戏目录", 
            "",
            QFileDialog.ShowDirsOnly
        )
        if path:
            path = path.replace("\\", "/")
            if "Counter-Strike Global Offensive" in path and "game" in path:
                self.cs2_path = path
                self.path_label.setText(f"Steam路径: {path}")
                self.path_label.setStyleSheet(f"""
                    QLabel {{
                        color: #2ECC71;
                        font-size: 14px;
                        padding: 12px;
                        background: rgba(46, 204, 113, 0.1);
                        border-radius: 8px;
                        border: 1px solid rgba(46, 204, 113, 0.3);
                        font-family: '{self.font_family}';
                    }}
                """)
                self.update_status("✅ 手动设置CS2路径成功")
                logging.info(f"手动设置CS2路径: {path}")
            else:
                QMessageBox.warning(self, "路径错误", "请选择正确的CS2游戏目录\n(应包含Counter-Strike Global Offensive/game)")
                logging.warning(f"选择了错误的路径: {path}")
                
    def update_autoexec(self):
        """更新autoexec.cfg配置"""
        if not self.cs2_path:
            QMessageBox.warning(self, "错误", "请先设置CS2路径")
            logging.warning("尝试更新配置但未设置CS2路径")
            return
            
        autoexec_path = os.path.join(self.cs2_path, "csgo", "cfg", "autoexec.cfg")
        autoexec_path = autoexec_path.replace("\\", "/")
        
        try:
            cfg_dir = os.path.dirname(autoexec_path)
            os.makedirs(cfg_dir, exist_ok=True)
            logging.info(f"确保配置目录存在: {cfg_dir}")
            
            config_lines = []
            if os.path.exists(autoexec_path):
                with open(autoexec_path, 'r', encoding='utf-8') as f:
                    config_lines = f.readlines()
                logging.info(f"读取现有配置文件: {autoexec_path}")
            
            original_count = len(config_lines)
            config_lines = [line for line in config_lines 
                          if not line.strip().startswith(('connect ', 'password '))]
            removed_count = original_count - len(config_lines)
            if removed_count > 0:
                logging.info(f"移除了 {removed_count} 行旧配置")
            
            server_addr = self.server_input.text().strip()
            password = self.password_input.text().strip()
            
            if server_addr:
                config_lines.append(f"connect {server_addr}\n")
                logging.info(f"添加服务器地址: {server_addr}")
            if password:
                config_lines.append(f'password "{password}"\n')
                logging.info("添加服务器密码")
            
            with open(autoexec_path, 'w', encoding='utf-8') as f:
                f.writelines(config_lines)
                
            self.update_status("✅ 配置文件更新成功")
            QMessageBox.information(self, "成功", "autoexec.cfg 配置已更新")
            logging.info(f"配置文件更新成功: {autoexec_path}")
            
        except Exception as e:
            error_msg = f"更新配置失败: {str(e)}"
            self.update_status(f"❌ {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)
            logging.error(error_msg)
            
    def launch_cs2(self):
        """启动CS2"""
        if not self.cs2_path:
            QMessageBox.warning(self, "错误", "请先设置CS2路径")
            logging.warning("尝试启动CS2但未设置路径")
            return
            
        possible_exe_paths = [
            os.path.join(self.cs2_path, "cs2.exe"),
            os.path.join(self.cs2_path, "bin", "win64", "cs2.exe")
        ]
        
        cs2_exe = None
        for exe_path in possible_exe_paths:
            exe_path = exe_path.replace("\\", "/")
            if os.path.exists(exe_path):
                cs2_exe = exe_path
                break
                
        if not cs2_exe:
            error_msg = f"找不到cs2.exe文件，已检查路径:\n" + "\n".join(possible_exe_paths)
            QMessageBox.warning(self, "错误", error_msg)
            logging.error(f"找不到cs2.exe文件: {possible_exe_paths}")
            return
            
        try:
            server_addr = self.server_input.text().strip()
            password = self.password_input.text().strip()
            
            launch_args = [cs2_exe]
            if server_addr:
                launch_args.extend(["+connect", server_addr])
            if password:
                launch_args.extend(["+password", f'"{password}"'])
            
            working_dir = os.path.dirname(cs2_exe)
            subprocess.Popen(launch_args, cwd=working_dir)
            
            launch_info = f"CS2启动成功\n可执行文件: {cs2_exe}"
            if server_addr:
                launch_info += f"\n服务器: {server_addr}"
            
            self.update_status("🚀 CS2启动成功")
            QMessageBox.information(self, "成功", launch_info)
            logging.info(f"CS2启动成功: {' '.join(launch_args)}")
            
        except Exception as e:
            error_msg = f"启动CS2失败: {str(e)}"
            self.update_status(f"❌ {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)
            logging.error(error_msg)
            
    def clear_console(self):
        """清空控制台日志"""
        self.console_text.clear()
        logging.info("控制台日志已清空")
        
    def update_status(self, message):
        """更新状态标签"""
        self.status_label.setText(message)
        
    def load_settings(self):
        """加载设置"""
        saved_path = self.config.get("cs2_path", "")
        if saved_path and os.path.exists(saved_path):
            self.cs2_path = saved_path
            self.path_label.setText(f"Steam路径: {saved_path}")
            self.path_label.setStyleSheet(f"""
                QLabel {{
                    color: #2ECC71;
                    font-size: 14px;
                    padding: 12px;
                    background: rgba(46, 204, 113, 0.1);
                    border-radius: 8px;
                    border: 1px solid rgba(46, 204, 113, 0.3);
                    font-family: '{self.font_family}';
                }}
            """)
            logging.info(f"加载保存的CS2路径: {saved_path}")
            
        # 加载窗口几何信息
        geometry = self.config.get("window_geometry", {})
        if geometry:
            self.move(geometry.get("x", 100), geometry.get("y", 100))
            

    def closeEvent(self, event):
        """窗口关闭事件"""
        # 保存窗口位置
        pos = self.pos()
        self.config.set("window_geometry", {"x": pos.x(), "y": pos.y()})
        
        # 保存服务器设置
        self.config.set("server_address", self.server_input.text())
        self.config.set("server_password", self.password_input.text())
        
        # 保存CS2路径
        if self.cs2_path:
            self.config.set("cs2_path", self.cs2_path)
            
        self.config.save_config()
        logging.info("设置已保存")
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    launcher = CS2Launcher()
    launcher.show()
    sys.exit(app.exec_())